package com.lepai.component;

import com.lepai.message.ResponseMessage;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.Map;

/**
 * @author "Ren PengFei (ROC)"
 * @date 2016年11月18日 下午3:23:14
 * @description 自定义ResponseMapping，将控制器任意返回对象转换为ResponseMessage
 */
public class ResponseMappingJackson2JsonView extends MappingJackson2JsonView {

    /**
     * (non-Javadoc)
     *
     * @see org.springframework.web.servlet.view.json.MappingJackson2JsonView#filterModel(java.util.Map)
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    protected Object filterModel(Map<String, Object> model) {
        Object result = super.filterModel(model);
        ResponseMessage response = new ResponseMessage();
        response.setCode("00");
        response.setMessage("SUCCESS");
        response.setTimestamp(System.currentTimeMillis());

        Object output = result;
        if (result instanceof Map) {
            if (((Map) result).size() == 1) {
                output = ((Map) result).values().iterator().next();
            }
        }


        response.setResult(output);
        return response;
    }

}

